<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use DB;
use App\Models\UserModel;
use App\Models\UserProfileModel;
use App\Http\Controllers\Controller;
use App\Http\Components\SmsComponent;
use App\Http\Components\UserComponent;

/**
 * 绑定新手机号
 */
class ChangePhoneController extends UserController{

    public function __construct(){
        parent::__construct();        
    }

    /*版本控制，对应app版本跳转对应接口*/
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            try{
                return $this->change_phone($request);
            }catch(\Exception $e){
                return $this->json('0','系统错误'.$e->getMessage());
            }
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    /**
     * 绑定新手机号
     */
    public function change_phone(Request $request){
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];
        $customAttr = [
            'userphone' => '用户名（手机号）',
            'check_code' => '验证码',
        ];
        $this->validate($request, [
            'userphone' => 'required|numeric',
            'check_code' => 'required',
        ],[ ], $customAttr);

        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];
        $user_phone = $request->input('userphone');
        $check_code = $request->input('check_code');
        //判断验证码是否正确
        $sms = new SmsComponent();

        $sms_status = $sms->verify_check_code($user_phone,$check_code,'change');
        if($sms_status){
            $userModel = UserModel::where("user_id",$user_id)->first();
            $userModel->user_id = $user_id;
            $userModel->phone = $user_phone;
            $userModel->saveOrFail();

            $UserProfileModel = UserProfileModel::where("user_id",$user_id)->first();
            $UserProfileModel->user_id = $user_id;
            $UserProfileModel->phone = $user_phone;
            $UserProfileModel->saveOrFail();
            $user_token = UserComponent::get_token($user_phone,$user["app_login_time"],$user["app_type"]);
            $data = array();
            $data['user_id'] = $user_id;
            $data['user_token'] = $user_token;
            return $this->json('1','操作成功',$data);

        }else{
            return $this->json('0',$sms->error_msg);
        }

    }
}
